package online.lmds.sdmanage.filter;


import online.lmds.sdmanage.common.entity.Result;
import online.lmds.sdmanage.common.utils.JsonUtils;
import online.lmds.sdmanage.main.authentication.entity.User;
import online.lmds.sdmanage.main.authentication.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


public class AuthInterceptor extends HandlerInterceptorAdapter {
    
    @Resource(name = "UserService")
    private UserService userService;

    public final static String[] IGNORE_AUTH_URL = {"/post/save", "/post/reply/save"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        String url = request.getRequestURI();

        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)) {
            return true;
        }
        User user = new User();
        user.setToken(token);
        Result result = userService.getByToken(user);
        if (result.isSuccess()) {
            User userGet = (User) result.getData();
            request.setAttribute("userId", userGet.getId());
            return true;
        }
        
        response.setCharacterEncoding("utf-8");
        response.addHeader("Content-Type", "application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(JsonUtils.objectToString(result));
        writer.flush();
        writer.close();
        return false;
        

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
